//
//  RNotesViewController.m
//  Riji
//
//  Created by liujianlong on 2022/8/18.
//

#import "RNotesViewController.h"
#import "RNoteCell.h"
#import "RSearchViewController.h"
#import "REditNoteViewController.h"
#import "RNoteInfoViewController.h"
#import "RLoginViewController.h"
@interface RNotesViewController ()
@property (weak, nonatomic) IBOutlet UIButton *addBtn;
@property (weak, nonatomic) IBOutlet UIView *nodataView;
@property (nonatomic, strong) NSMutableArray *data;
@property (nonatomic, strong) UIButton *rightBtn;
@end

@implementation RNotesViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
    [self loadData];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadData) name:notifyNoteUpdate object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadData) name:notifyUserUpdate object:nil];

}
- (void)initUI{
    
    if (self.type == NotesTypeNormal) {
        self.title = LS(@"日记");
        self.navigationItem.leftBarButtonItem = nil;
        [self.rightBtn setImage:[UIImage imageNamed:@"搜索"] forState:UIControlStateNormal];
    }else{
        self.title = LS(@"回收站");
        self.addBtn.hidden = YES;
        [self.rightBtn setTitle:LS(@"清空") forState:UIControlStateNormal];
        //添加长按事件
        UILongPressGestureRecognizer *gesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(didLongPressTableViewCell:)];
        gesture.minimumPressDuration = 1.0;
        [self.tableView addGestureRecognizer:gesture];
    }
    self.nodataView.hidden = YES;
    [self.tableView registerNib:[RNoteCell nib] forCellReuseIdentifier:[RNoteCell ID]];
    [self.view sendSubviewToBack:self.tableView];
}

- (UIButton *)rightBtn{
    if (!_rightBtn) {
        _rightBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, StuBarHight + 5, 40, 40)];
        [_rightBtn addTarget:self action:@selector(actionForRightBtn:) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightBtn];
    }
    return _rightBtn;
}
#pragma mark - 获取缓存日记数据
- (void)loadData{
    [RLHud startHud:LS(@"获取数据中...")];
    self.data = [NSMutableArray array];
    int stamp = [[NSDate currentTimeStamp:@"yyyy/MM/dd"] intValue];
    NSDateComponents *com = [NSDate dateOfStamp:stamp];
    ///获取最近十年的数据
    for (int i = (int)com.year + 10; i >= com.year; i--) {
        for (int j = 12 ; j >= 1; j--) {
            NSString* where = [NSString stringWithFormat:@"where %@=%@ and %@=%@ and %@=%@ and %@=%@",bg_sqlKey(@"ID"),bg_sqlValue(APP.user.ID),bg_sqlKey(@"year"),bg_sqlValue(@(i)),bg_sqlKey(@"month"),bg_sqlValue(@(j)),bg_sqlKey(@"remove"),bg_sqlValue(@(self.type == NotesTypeRecycle))];
            NSArray *array = [RNoteModel bg_find:nil where:where];
            if (array.count > 0) {
                NSString *str = [NSString stringWithFormat:LS(@"%d年%d月"),i,j];
                [self.data addObject:@{str:array}];
            }
        }
    }
    [RLHud stopHud];
    [self.tableView reloadData];
    self.nodataView.hidden = [self.data count] > 0;
    
}
#pragma mark - 长按手势
- (void)didLongPressTableViewCell:(UILongPressGestureRecognizer *)gesture
{
    if (gesture.state == UIGestureRecognizerStateBegan) {
        //获取到点击的位置
        CGPoint point = [gesture locationInView:self.tableView];
        NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:point];
        if(indexPath == nil) return;
        RDeletePopViewController *vc = [RDeletePopViewController new];
        vc.titles = @[@"移出回收站",@"彻底删除"];
        vc.viewBottom.constant = SCREEN_HEIGHT - point.y;
        vc.deleteBlock = ^(NSString * title) {
            NSDictionary*dict = self.data[indexPath.section];
            NSString *key = [[dict allKeys] firstObject];
            NSMutableArray *array = [NSMutableArray arrayWithArray:dict[key]];
            RNoteModel *model = array[indexPath.row];
            if ([title isEqualToString:@"移出回收站"]) {
                model.remove = NO;
                [array removeObject:model];
                [model bg_saveOrUpdate];
                [[NSNotificationCenter defaultCenter] postNotificationName:notifyNoteUpdate object:nil];
                [self.navigationController popToRootViewControllerAnimated:YES];
            }else if ([title isEqualToString:@"彻底删除"]){
                NSString* where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"stamp"),bg_sqlValue(@(model.stamp))];
                [RNoteModel bg_deleteAsync:nil where:where complete:^(BOOL isSuccess) {}];
                [array removeObject:model];
            }
            [self.data replaceObjectAtIndex:indexPath.section withObject:@{key:array}];
            [self.tableView reloadData];
        };
        [self presentViewController:vc animated:NO completion:nil];
        //do something...
    }
}
#pragma mark - 搜索日记  / 清空回收站
- (void)actionForRightBtn:(UIButton*)sender{
    if (self.type == NotesTypeNormal) {
        RSearchViewController *vc = [RSearchViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        RPopAlertViewController *vc = [RPopAlertViewController new];
        vc.msgLbl.text = LS(@"确定清空回收站吗？");
        vc.enterBlock = ^(NSString * _Nonnull string) {
            [Tool clearRecycleBin:^{
                [self.navigationController popToRootViewControllerAnimated:YES];
            }];
        };
        [self presentViewController:vc animated:NO completion:nil];
    }
}
#pragma mark - 开始记录日记
- (IBAction)actionForAddNotes:(UIButton *)sender {
    [self.navigationController pushViewController:[REditNoteViewController new] animated:YES];
}
#pragma mark - 点击时间/定位/天气/心情
- (void)clickSubItem:(NSIndexPath *)indexpath tag:(int)tag{
    NSLog(@"====》〉》。  section = %ld  row = %d   tag = %d",(long)indexpath.section, indexpath.row, tag);
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.data.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *array = [[self.data[section] allValues] firstObject];
    return  array.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    RNoteCell *cell = [tableView dequeueReusableCellWithIdentifier:[RNoteCell ID]];
    NSArray *array = [[self.data[indexPath.section] allValues] firstObject];
    cell.model = array[indexPath.row];
    WS(self)
    cell.selectItem = ^(int tag) {
        [weakself clickSubItem:indexPath tag:tag];
    };
    return  cell;
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return self.type == NotesTypeNormal ? 36 : 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (self.type == NotesTypeNormal) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 36)];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 36)];
        label.text = [[self.data[section] allKeys] firstObject];;
        label.textHexColor = @"#2F88EE";
        label.textAlignment = NSTextAlignmentCenter;
        view.backGroudHexColor = @"#F7F7F7";
        [view addSubview:label];
        return view;
    }else{
        return nil;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    RNoteInfoViewController *VC = [RNoteInfoViewController new];
    VC.type = self.type;
    VC.index = (int)indexPath.row;
    VC.array = [[self.data[indexPath.section] allValues] firstObject];
    [self.navigationController pushViewController:VC animated:YES];
}

@end
